home *** CD-ROM | disk | FTP | other *** search
/ Freelog 117 / FreelogNo117-OctobreNovembre2013.iso / Programmation / jedit / jedit5.1.0install.exe / {app} / macros / Java / Make_Get_and_Set_Methods.bsh < prev    next >
Text File  |  2013-07-28  |  16KB  |  429 lines

  1. /**
  2. Make_Get_and_Set_Functions.bsh - a BeanShell macro for
  3. the jEdit text editor  that creates simple get() and set()
  4. methods for the variables on selected lines.
  5.  
  6. Copyright (C)  2004 Thomas Galvin - software@thomas-galvin.com
  7. based on Make_Get_and_Set_Methods.bsh by John Gellene
  8.  
  9. This macro will work on multiple selected lines; for instance,
  10. selecting
  11.  
  12. <code>
  13. public int foo;
  14. public int bar;
  15. </code>
  16.  
  17. and running the macro will produce get and set functions for both
  18. variables, along with comments.  This macro produces c-style
  19. functions, unless the buffer is in java mode.
  20.  
  21. Modifications by Dale Anson, Dec 2008:
  22.  
  23. 1. Allows variable declarations to have an initial assignment, like
  24. <code>
  25. public int foo = 1;
  26. public int bar = 2;
  27. </code>
  28.  
  29. 2. Allows multiple variables on same line, like
  30. <code>
  31. public int foo, bar;
  32. </code>
  33.  
  34. 3. Use line separator as set in buffer properties rather than always using \n.
  35.  
  36. This program is free software; you can redistribute it and/or
  37. modify it under the terms of the GNU General Public License
  38. as published by the Free Software Foundation; either version 2
  39. of the License, or any later version.
  40.  
  41. This program is distributed in the hope that it will be useful,
  42. but WITHOUT ANY WARRANTY; without even the implied warranty of
  43. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  44. GNU General Public License for more details.
  45. */
  46.  
  47. // Localization
  48. final static String DONE = jEdit.getProperty("macro.rs.MakeGetAndSetMethods.GenerateCode.label", "Generate Code");
  49. final static String CANCEL = jEdit.getProperty("common.cancel");
  50. final static String CreateGetMethodsLabel = jEdit.getProperty("macro.rs.MakeGetAndSetMethods.CreateGetMethods.label", "Create Get Methods");
  51. final static String CreateSetMethodsLabel = jEdit.getProperty("macro.rs.MakeGetAndSetMethods.CreateSetMethods.label", "Create Set Methods");
  52. final static String CreateGetandSetMethodsLabel = jEdit.getProperty("macro.rs.MakeGetAndSetMethods.CreateGetandSetMethods.label", "Create Get and Set Methods");
  53.     
  54. //Process
  55. boolean JAVA_MODE = buffer.getMode().getName().equals( "java" );
  56.  
  57. // use line separator from current buffer
  58. String LS = buffer.getStringProperty( "lineSeparator" );
  59. if (LS == null) {
  60.     // otherwise, use default line separator
  61.     LS = jEdit.getProperty("buffer.lineSeparator");   
  62. }
  63.  
  64. boolean createGetMethods = true;
  65. boolean createSetMethods = true;
  66.  
  67. void setCaret( int selectionStart, int selectionEnd ) {
  68.     textArea.setCaretPosition( selectionStart );
  69.     textArea.moveCaretPosition( selectionEnd );
  70. }
  71.  
  72. String getClassName() {
  73.     int selectionStart;
  74.     int selectionEnd;
  75.     if(textArea.getSelection().length != 0){  // if there are selections exists
  76.         selectionStart = textArea.getSelection(0).getStart();
  77.         selectionEnd = textArea.getSelection(0).getEnd();
  78.     }
  79.     else {        // if no selection
  80.         selectionStart = textArea.getCaretPosition();
  81.         selectionEnd = textArea.getCaretPosition();
  82.     }
  83.  
  84.     String text = textArea.getText();
  85.     int index = text.lastIndexOf( "class", selectionStart );
  86.     if ( index != -1 ) {
  87.         textArea.setCaretPosition( index );
  88.         int lineNumber = textArea.getCaretLine();
  89.         int lineEnd = textArea.getLineEndOffset( lineNumber );
  90.         String lineText = text.substring( index, lineEnd );
  91.  
  92.         StringTokenizer tokenizer = new StringTokenizer( lineText );
  93.         tokenizer.nextToken(); //eat "class"
  94.         if ( tokenizer.hasMoreTokens() ) {
  95.             setCaret( selectionStart, selectionEnd );
  96.             return tokenizer.nextToken();
  97.         }
  98.     }
  99.     setCaret( selectionStart, selectionEnd );
  100.  
  101.     String fileClassName = buffer.getName();
  102.     int index = fileClassName.lastIndexOf( '.' );
  103.     if ( index != -1 ) {
  104.         fileClassName = fileClassName.substring( 0, index );
  105.         if ( fileClassName.toLowerCase().indexOf( "untitled" ) == -1 ) {
  106.             return fileClassName;
  107.         }
  108.     }
  109.  
  110.     return "";
  111. }
  112.  
  113. String createJavaGetMethod( String type, String variableName ) {
  114.     String uppperVariable = Character.toUpperCase( variableName.charAt( 0 ) ) + variableName.substring( 1, variableName.length() );
  115.     String result =
  116.         "\t/**" + LS +
  117.         "\t * Returns the value of " + variableName + "." + LS +
  118.         "\t */" + LS +
  119.         "\tpublic " + type + " get" + uppperVariable + "() {" + LS +
  120.         "\t\treturn " + variableName + ";" + LS +
  121.         "\t}" + LS;
  122.  
  123.     return result;
  124. }
  125.  
  126. String createJavaSetMethod( String type, String variableName ) {
  127.     String uppperVariable = Character.toUpperCase( variableName.charAt( 0 ) ) + variableName.substring( 1, variableName.length() );
  128.     String result =
  129.         "\t/**" + LS +
  130.         "\t * Sets the value of " + variableName + "." + LS +
  131.         "\t * @param " + variableName + " The value to assign " + variableName + "." + LS +
  132.         "\t */" + LS +
  133.         "\tpublic void set" + uppperVariable + "(" + type + " " + variableName + ") {" + LS +
  134.         "\t\tthis." + variableName + " = " + variableName + ";" + LS +
  135.         "\t}" + LS;
  136.  
  137.     return result;
  138. }
  139.  
  140. String createCppGetMethod( String className, String type, String variableName ) {
  141.     String scopeIndicator = "";
  142.     if ( className != null && className.compareTo( "" ) != 0 ) {
  143.         scopeIndicator = className + "::";
  144.     }
  145.     if (type == null) {
  146.         type = "";   
  147.     }
  148.     String uppperVariable = Character.toUpperCase( variableName.charAt( 0 ) ) + variableName.substring( 1, variableName.length() );
  149.     String result =
  150.         "/*" + LS +
  151.         "function: get" + uppperVariable + "()" + LS +
  152.         "Returns the value of " + variableName + "." + LS +
  153.         "*/" + LS +
  154.         type + (type.length() > 0 ? " " : "") + scopeIndicator + "get" + uppperVariable + "()" + "" + LS +
  155.         "{" + "" + LS +
  156.         "  return " + variableName + ";" + "" + LS +
  157.         "}" + LS;
  158.  
  159.     return result;
  160. }
  161.  
  162. String createCppSetMethod( String className, String type, String variableName ) {
  163.     String scopeIndicator = "";
  164.     if ( className != null && className.compareTo( "" ) != 0 ) {
  165.         scopeIndicator = className + "::";
  166.     }
  167.  
  168.     String uppperVariable = Character.toUpperCase( variableName.charAt( 0 ) ) + variableName.substring( 1, variableName.length() );
  169.     String setVariable = variableName + "Value";
  170.     String result =
  171.         "/*" + LS +
  172.         "function: set" + uppperVariable + "()" + LS +
  173.         "Sets the value of " + variableName + "." + LS +
  174.         "Input: " + setVariable + " The value to assign " + variableName + "." + LS +
  175.         "*/" + LS +
  176.         "void " + scopeIndicator + "set" + uppperVariable + "(const " + type + "& " + setVariable + ")" + LS +
  177.         "{" + "" + LS +
  178.         "  " + variableName + " = " + setVariable + ";" + "" + LS +
  179.         "}" + LS;
  180.  
  181.     return result;
  182. }
  183.  
  184. void parseSelection() {
  185.     // offsets from start of buffer
  186.     int selectionStart;
  187.     int selectionEnd;
  188.     if (textArea.getSelection().length() == 0) {
  189.         // no selection, use current line
  190.         selectionStart = textArea.getLineStartOffset(textArea.getCaretLine());
  191.         selectionEnd = textArea.getLineEndOffset(textArea.getCaretLine());
  192.     }
  193.     else {
  194.         selectionStart = textArea.getSelection(0).getStart();
  195.         selectionEnd = textArea.getSelection(0).getEnd();
  196.     }
  197.  
  198.     StringBuffer code = new StringBuffer();
  199.     String className = getClassName();
  200.     
  201.     // remove comments and blank lines
  202.     ArrayList lines = stripComments(buffer, selectionStart, selectionEnd);
  203.     if (lines.size() == 0) {
  204.         return;   
  205.     }
  206.     
  207.     // parse each line for variable declaration. Lines are already trimmed and
  208.     // have all comments removed.
  209.     for (int i = 0; i < lines.size(); i++) {
  210.         String lineText = lines.get(i);
  211.         
  212.         // combine lines up to next semi-colon into a single line
  213.         while(!lineText.endsWith(";") && i < lines.size()) {
  214.             lineText += lines.get(++i);   
  215.         }
  216.         
  217.         // ensure line contains at least two words, that is, a type
  218.         // and a variable name at minimum. This is a fairly lame check in that
  219.         // "public int" would qualify, but it does mean that I don't have to
  220.         // do so much bounds checking below.
  221.         if (!lineText.matches("\\S+\\s+[_A-Za-z0-9$]+.*?")) {
  222.             continue;   
  223.         }
  224.         
  225.         // remove semi-colon
  226.         if ( lineText.endsWith( ";" ) ) {
  227.             lineText = lineText.substring( 0, lineText.length() - 1 );
  228.         }
  229.         lineText = lineText.trim();
  230.         if ( lineText.length() == 0 ) {
  231.             continue;
  232.         }
  233.         
  234.         // list to hold variable names
  235.         ArrayList variables = new ArrayList();
  236.         
  237.         // the variable type
  238.         String type = "";
  239.         
  240.         // could have declaration like "int x, y = 6;", which is why there
  241.         // needs to be an array for the variable names
  242.         if ( lineText.indexOf( "," ) > 0 ) {
  243.             int comma = lineText.indexOf(",");
  244.             String front = lineText.substring(0, comma);        // everything before the first comma
  245.             if (front.indexOf("=") > 0) {
  246.                 front = front.substring(0, front.indexOf("=")); // drop the initial value  
  247.             }
  248.             front = front.trim();
  249.             String[] fronts = front.split("\\s+");
  250.             variables.add(fronts[fronts.length - 1]);           // last item in array is variable name
  251.             type = fronts[fronts.length - 2];                   // next to last item is type
  252.  
  253.             String back = lineText.substring(comma + 1);        // everything after the first comma
  254.             String[] backs = back.split(",");
  255.             for (back : backs) {
  256.                 back = back.trim();
  257.                 String[] parts = back.split("\\s+");            // could have initializer with spaces
  258.                 String var = extractVar(parts[0]);              // could have i=0, ie, no spaces
  259.                 variables.add(var);   
  260.             }
  261.         }
  262.         else {
  263.             // just one variable declared, may be initialized
  264.             if (lineText.indexOf("=") > 0) {
  265.                 lineText = lineText.substring(0, lineText.indexOf("="));    // drop the intial value
  266.             }
  267.             lineText = lineText.trim();
  268.             String[] parts = lineText.split("\\s+");
  269.             variables.add(extractVar(parts[parts.length - 1])); // last item in array is variable name
  270.             type = parts[parts.length - 2];                     // next to last item is type
  271.         }
  272.         
  273.         type = type.trim();
  274.         
  275.         if (variables.size() == 0) {
  276.             continue;   
  277.         }
  278.         code.append( LS );
  279.  
  280.         // create the get and set methods for each variable
  281.         for ( String variable : variables ) {
  282.             if ( createGetMethods ) {
  283.                 String tmp = JAVA_MODE ? createJavaGetMethod( type, variable ) : createCppGetMethod( className, type, variable );
  284.                 if ( tmp != null && tmp.length() > 0 ) {
  285.                     code.append( tmp ).append( LS );
  286.                 }
  287.             }
  288.  
  289.             if ( createSetMethods && lineText.indexOf( "final " ) == -1 && lineText.indexOf( "const " ) == -1 ) {
  290.                 String tmp = JAVA_MODE ? createJavaSetMethod( type, variable ) : createCppSetMethod( className, type, variable );
  291.                 if ( tmp != null && tmp.compareTo( "" ) != 0 ) {
  292.                     code.append( LS ).append( tmp ).append( LS );
  293.                 }
  294.             }
  295.         }
  296.     }
  297.  
  298.     String toInsert = code.toString();
  299.     if (toInsert.trim().length() == 0) {
  300.         return;   
  301.     }
  302.     
  303.     // move to the end of the selected text
  304.     textArea.setCaretPosition( selectionEnd );
  305.  
  306.     // insert get/set methods
  307.     textArea.setSelectedText( toInsert );
  308.  
  309.     // select the inserted code and indent it
  310.     textArea.setCaretPosition( selectionEnd );
  311.     textArea.moveCaretPosition( selectionEnd + code.length(), true );
  312.     textArea.indentSelectedLines();
  313. }
  314.  
  315. import org.gjt.sp.jedit.syntax.*;
  316.  
  317. // Given the buffer and start and end of the selection, remove comments and 
  318. // blank lines, then return a list of the remaining lines. The list contains 
  319. // the trimmed line text.
  320. ArrayList stripComments( Buffer buffer, int startOffset, int endOffset ) {
  321.     int firstLine = buffer.getLineOfOffset(startOffset);
  322.     
  323.     // the last line may not actually have anything selected, just the caret
  324.     // happens to be at the start of the line or include part of the whitespace
  325.     // at the start of the line. In this case, don't include the last line.
  326.     int lastLine = buffer.getLineOfOffset(endOffset);
  327.     String lastLineText = buffer.getText(buffer.getLineStartOffset(lastLine), endOffset - buffer.getLineStartOffset(lastLine));
  328.     if (lastLineText.trim().length() == 0) {
  329.         --lastLine;   
  330.     }
  331.     
  332.     ArrayList lines = new ArrayList();
  333.     DefaultTokenHandler tokenHandler = new DefaultTokenHandler();
  334.     StringBuilder lineBuffer = new StringBuilder();
  335.     
  336.     for ( int lineNum = firstLine; lineNum <= lastLine; lineNum++ ) {
  337.         int lineStart = buffer.getLineStartOffset(lineNum);
  338.         lineBuffer.delete(0, lineBuffer.length());
  339.  
  340.         tokenHandler.init();
  341.         buffer.markTokens( lineNum, tokenHandler );
  342.         Token token = tokenHandler.getTokens();
  343.         
  344.         // skip comments
  345.         while(token.id != Token.END) {
  346.             if (token.id < Token.COMMENT1 || token.id > Token.COMMENT4) {
  347.                 lineBuffer.append(buffer.getText(lineStart + token.offset, token.length));
  348.             }
  349.             token = token.next;   
  350.         }
  351.         
  352.         String line = lineBuffer.toString().trim();
  353.         
  354.         // skip blank lines
  355.         if (line.length() > 0) {
  356.             lines.add(line.trim());
  357.         }
  358.     }
  359.     return lines;
  360.  
  361. boolean isWhitespace(Token token) {
  362.     String text = buffer.getText(token.offset, token.length);
  363.     return text.trim().length() == 0;
  364. }
  365.  
  366. // given something line "a = 6", returns just the "a". 
  367. String extractVar(String var) {
  368.     if (var == null) {
  369.         return "";   
  370.     }
  371.     var = var.trim();
  372.     if (var.indexOf("=") > 0) {
  373.         var = var.substring(0, var.indexOf("=")).trim();
  374.     }
  375.     return var;
  376. }
  377.  
  378. void displayPrompt() {
  379.     JCheckBox getCheckbox = new JCheckBox( CreateGetMethodsLabel, true );
  380.     JCheckBox setCheckbox = new JCheckBox( CreateSetMethodsLabel, true );
  381.  
  382.     JPanel checkBoxPanel = new JPanel(new BorderLayout());
  383.     checkBoxPanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
  384.     checkBoxPanel.add( getCheckbox, BorderLayout.NORTH );
  385.     checkBoxPanel.add( setCheckbox, BorderLayout.SOUTH );
  386.  
  387.     JButton createButton = new JButton( DONE );
  388.     JButton cancelButton = new JButton( CANCEL );
  389.  
  390.     JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 6, 0));
  391.     buttonPanel.setBorder(BorderFactory.createEmptyBorder(11, 11, 11, 11));
  392.     buttonPanel.add( createButton, BorderLayout.WEST );
  393.     buttonPanel.add( cancelButton, BorderLayout.EAST );
  394.  
  395.     JPanel mainPanel = new JPanel();
  396.     mainPanel.setLayout( new BorderLayout() );
  397.     mainPanel.add( checkBoxPanel, BorderLayout.NORTH );
  398.     mainPanel.add( buttonPanel, BorderLayout.SOUTH );
  399.  
  400.     JDialog dialog = new JDialog( view, CreateGetandSetMethodsLabel, false );
  401.     dialog.setContentPane( mainPanel );
  402.  
  403.     actionPerformed( ActionEvent e ) {
  404.         if ( e.getSource() == createButton ) {
  405.             createGetMethods = getCheckbox.isSelected();
  406.             createSetMethods = setCheckbox.isSelected();
  407.             parseSelection();
  408.         }
  409.         this.dialog.dispose();
  410.         return ;
  411.     }
  412.  
  413.     createButton.addActionListener( this );
  414.     cancelButton.addActionListener( this );
  415.  
  416.     dialog.pack();
  417.     dialog.setLocationRelativeTo( view );
  418.     dialog.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
  419.     dialog.setVisible( true );
  420.     createButton.requestFocus();
  421. }
  422.  
  423.  
  424. final static String NotEditableMessage = jEdit.getProperty("macro.rs.general.ErrorNotEditableDialog.message", "Buffer is not editable");
  425. if ( buffer.isReadOnly() )
  426.     Macros.error( view, NotEditableMessage );
  427. else
  428.     displayPrompt();